<template>
  <div>
    <div>
      <van-divider>群组管理</van-divider>
      <van-row type="flex" justify="space-around">
        <van-col>
          <van-field
            readonly
            clickable
            name="picker"
            :value="selectedGroup"
            label="群组"
            placeholder="选择群组"
            @click="showPicker = true"
          />
          <van-popup v-model="showPicker" position="bottom">
            <van-picker
              show-toolbar
              :columns="groupColumns"
              @confirm="onSwitchGroup"
              @cancel="showPicker = false"
            />
          </van-popup>
        </van-col>
        <van-col>
          <van-button
            @click="onShowGroupAddForm"
            style="margin: 10px 0 0 0"
            size="mini"
            icon="plus"
            type="primary"
          />
        </van-col>
      </van-row>
      <van-tabs>
        <van-tab title="图片管理">
          <van-row type="flex" justify="space-between" style="height: 30px">
            <van-col span="20">
              <van-notice-bar
                style="height: 100%"
                color="#1989fa"
                background="#ecf9ff"
                left-icon="info-o"
              >长按删除</van-notice-bar>
            </van-col>
            <van-col span="3">
              <van-button style="height: 100%" @click="onShowImgAddForm" size="small" icon="add-o" />
            </van-col>
            <van-popup
              v-model="imgManager.imgAddForm.show"
              round
              position="bottom"
              :style="{ height: '60%' }"
            >
              <van-form style="padding: 40px" @submit="onSubmit">
                <van-field v-model="imgManager.imgAddForm.nickName" name="nickName" label="人物昵称" placeholder="人物昵称" />
                <van-divider>图片提交</van-divider>
                <van-uploader v-model="imgManager.imgAddForm.imgList" multiple :max-count="1" :after-read="setImgUploadFile" />
                <div style="margin: 16px">
                  <van-button @click="submitAddImage" round block type="info" native-type="submit">提交</van-button>
                </div>
              </van-form>
            </van-popup>
          </van-row>
          <div style="justify-content: space-between">
            <van-image
              style="padding: 10px 10px"
              v-for="item in imageList"
              v-longpress="() => showDeleteImgModal(item)"
              :key="item.fileHash"
              width="45%"
              :src="mapHashToUrlWait(item.fileHash)"
              fit="scale-down"
            >
              <template v-slot:loading>
                <van-loading type="spinner"/>
              </template>
              <template v-slot:default>
                <p style="text-align: center">{{ item.nickName }}</p>
              </template>
            </van-image>
          </div>
        </van-tab>
        <van-tab title="成员管理">
          <van-row>
            <van-col style="padding: 0 7px" offset="1">
              <van-button @click="onGenInviteTicket" type="info" size="mini">邀请码</van-button>
            </van-col>
            <van-col style="padding: 0 7px">
              <van-button @click="onInvite" type="info" size="mini">邀请</van-button>
            </van-col>
            <van-col style="padding: 0 7px">
              <van-button @click="onJoinInviteTicket" type="info" size="mini">加入邀请</van-button>
            </van-col>
            <van-col style="padding: 0 7px" offset="8">
              <van-button @click="onExpellGroup" type="danger" size="mini">踢出组</van-button>
            </van-col>
          </van-row>
          <van-search
            v-model="group.searchInput"
            show-action
            placeholder="账号或昵称"
            @search="onSearch"
            shape="round"
          >
            <template #action>
              <div @click="onSearch">搜索</div>
            </template>
          </van-search>
          <van-list
            v-model="group.userList.loading"
            :finished="group.userList.finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <Table ref="table" :tableData="group.userList.list" @selectTochLong="selectTableRow"></Table>
          </van-list>
        </van-tab>
      </van-tabs>
    </div>
    <keep-alive>
      <TabBar ref="tabBar" />
    </keep-alive>
    <van-popup
      v-model="group.groupAddForm.show"
      round
      position="bottom"
      :style="{
      height: '60%' }"
    >
      <van-form style="padding: 40px" @submit="onSubmit">
        <van-field v-model="group.groupAddForm.groupName" name="组名" label="组名" placeholder="组名" />
        <div style="margin: 16px">
          <van-button @click="submitAddGroup" round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </van-popup>
    <van-popup
      v-model="group.joinInviteTicketForm.show"
      round
      position="bottom"
      :style="{
      height: '60%' }"
    >
      <van-form style="padding: 40px">
        <van-field
          v-model="group.joinInviteTicketForm.inviteTicket"
          name="邀请码"
          label="邀请码"
          placeholder="输入邀请码"
        />
        <div style="margin: 16px">
          <van-button
            @click="submitJointInviteTicket"
            round
            block
            type="info"
            native-type="submit"
          >提交</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import TabBar from "../components/TabBar.vue";
import { Dialog } from "vant";
import Table from "../components/Table.vue";
import { mapGetters } from "vuex";
import { toClipboard } from "@soerenmartius/vue3-clipboard";
export default {
  components: { Table, TabBar },
  data() {
    return {
      active: false,
      imageCount: 0,
      imageList: [],
      imgManager: {
        imgAddForm: {
          // imgManager.imgAddForm.nickName
          nickName: "",
          show: false,
          // imgManager.imgAddForm.imgList
          imgList: [],
        },
        // mapgetters
        // imgList: [],
        imgUploadFile: null,
        imgUploadList: [],
      },
      username: "",
      group: {
        groupAddForm: {
          show: false,
        },
        joinInviteTicketForm: {
          show: false,
          inviteTicket: null,
        },
        searchInput: "A3",
        userList: {
          list: [
            {
              username: "3",
              nickName: "5",
              checked: false,
            },
            {
              username: "33344",
              nickName: "0ooi问3",
              checked: false,
            },
          ],
          finished: true,
          loading: true,
        },
      },
      value: "A3",
      // groupColumns: ["A3"],
      showPicker: false,
    };
  },
  watch: {
    group: {
      deep: true,
      handler(value) {
        console.log(value);
      },
    },
    "$store.state.image.imageList": {
      immediate: true,
      deep: true,
      handler(value) {
        console.log("enter watch $store.state.image.imageList, newSize: " + Object.keys(value).length);
        this.imageList = this.$store.getters["image/getImageList"];
      }
    },
    "$store.state.image.hashToUrl": {
      immediate: true,
      deep: true,
      handler(value) {
        console.log("enter watch $store.state.image.hashToUrl, newSize: " + Object.keys(value).length);
        this.imageList = this.$store.getters["image/getImageList"];
      }
    },
    '$store.state.group.groupMemberList': {
        immediate: true,
        deep: true,
        handler(value) {
          console.log("enter watch $store.state.group.groupMemberList")
          let groupMemberList = value || []
          this.group.userList.list = groupMemberList.map((dto) => {
            return {
              username: dto.username,
              nickName: dto.nickName,
              checked: false
            };
          });
           // update locally relevant data
        }
     },
  },
  computed: {
    ...mapGetters({
      groupColumns: "group/getGroupList",
      selectedGroup: "group/getSelectedGroup",
      mapHashToUrl: "image/mapHashToUrl",
      // imgList: "image/getImageList",
    }),
  },
  mounted: function () {let userToken = this.$store.state.user.userToken;
    if(userToken == null || userToken == "") {
      this.$router.push({path: "/login"});
    }
    console.log("mounted");
    this.$store.dispatch("group/listGroup");
  },
  methods: {
    mapHashToUrlWait(fileHash) {
      return this.mapHashToUrl(fileHash);
    },
    onLoad(e) {
      //TODELETE
    },
    setImgUploadFile(file) {
      this.imgManager.imgUploadFile = file;
    },
    onGenInviteTicket(e) {
      let callback = (ticket) => {
        Dialog.confirm({
          title: "邀请码",
          message: ticket,
          confirmButtonText: "复制",
        })
          .then(() => {
            toClipboard(ticket);
          })
          .catch(() => {});
      };
      this.$store.dispatch("group/genInviteTicket", { callback: callback });
    },
    onInvite(e) {
      
    },
    onJoinInviteTicket(e) {
      this.group.joinInviteTicketForm.inviteTicket = null;
      this.group.joinInviteTicketForm.show = true;
    },
    submitJointInviteTicket(e) {
      let ticket = this.group.joinInviteTicketForm.inviteTicket;
      if (!ticket) {
        return;
      }
      this.$store.dispatch("group/joinInviteTicket", {groupTicket: ticket});
    },
    onExpellGroup(e) {

    },
    onExpellGroup(e) {},
    onSubmit(e) {
      //TODELETE
    },
    onSwitchGroup(value, index) {
      this.$store.dispatch("group/loadSelectedGroup", {
        selectedIndex: index,
      });
      this.showPicker = false;
    },
    submitAddImage(e) {
      console.log("Enter submitAddImage");
      let file = this.imgManager.imgUploadFile;
      let nickName = this.imgManager.imgAddForm.nickName;
      if(file) {
        console.log("upload image: ");
        this.$store.dispatch("image/uploadImage", {nickName: nickName, file: file});
      }
      this.imgManager.imgAddForm.show = false;
      this.imgManager.imgAddForm.nickName = "";
      this.imgManager.imgUploadFile = null;
    },
    submitAddGroup(e) {
      let groupName = this.group.groupAddForm.groupName;
      this.$store.dispatch("group/createGroup", { groupName: groupName });
      this.group.groupAddForm.show = false;
    },
    onShowImgAddForm(e) {
      this.imgManager.imgAddForm.show = true;
    },
    onShowGroupAddForm(e) {
      this.group.groupAddForm.show = true;
    },
    showDeleteImgModal(imgDto) {
      Dialog.confirm({
        title: "删除图片",
        message: imgDto.name,
      })
        .then(() => {
          // on confirm
          // console.log(imgDto);
          this.$store.dispatch("image/deleteImage", imgDto);
          console.log("删除确认");
        })
        .catch(() => {
          console.log("删除取消");
          // on cancel
        });
    },
    onSearch() {
      let value = this.group.searchInput;
      console.log("search value: " + value);
    },
    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
    },
    selectTableRow(index) {
      this.$set(
        this.group.userList.list[index],
        "checked",
        !this.group.userList.list[index].checked
      );
      this.$refs.table.$forceUpdate();
    },
  },
};
</script>

<style lang="css" scoped>
.row {
  display: flex;
  justify-content: space-between;
}
</style>
